package com.ciaojian.core.service;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ciaojian.core.mapper.UserTimesCardMapper;
import com.ciaojian.core.model.User;
import com.ciaojian.core.model.UserTimesCard;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

/**
 * @author oxiny
 */
public abstract class UserTimesCardService<M extends BaseMapper<T>, T> extends ServiceImpl<UserTimesCardMapper, UserTimesCard> {
    /**
     * 根据ID查询
     *
     * @param id /
     * @return /
     */
    public Optional<UserTimesCard> selectById(Integer id) {
        return Optional.ofNullable(this.baseMapper.selectById(id));
    }


    /**
     * 查询用户次卡信息
     *
     * @param userId 用户ID
     * @param cardId 次卡ID
     * @return 用户次卡信息
     */
    public Optional<UserTimesCard> getByUserIdAndCardId(Integer userId, Integer cardId) {
        return Optional.ofNullable(this.baseMapper.getByUserIdAndCardId(userId, cardId));
    }

    /**
     * 检查用户是否开通了这张次卡
     *
     * @param user        用户
     * @param timesCardId 次卡ID
     * @return -1:未开过会员 0:0开过会员但已过期 1有效会员
     */
    public int checkTimesCard(User user, int timesCardId) {
        UserTimesCard userTimesCard = this.lambdaQuery()
                .eq(UserTimesCard::getUserId, user.getId())
                .eq(UserTimesCard::getCardId, timesCardId).one();
        // 如果没数据表示从未开过会员
        if (userTimesCard == null) {
            return -1;
        }
        // 如果到期日在当前日之后,返回 1 表示是会员;0 表示曾经开过会员但已过期
        return userTimesCard.getDueDate().after(new Date()) ? 1 : 0;
    }

    /**
     * 生成当前日期时间串
     *
     * @return TC + 当前时间戳字符串
     */
    public final String generateOrderNo() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        return "TC".concat(sdf.format(date));
    }
}
